package com.tianheng.wanzhou.datacollecting.netty.bingtiaoji;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.Cushaji;
import com.tianheng.wanzhou.datacollecting.db.entity.DrawFrame1000005;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.ICushajiService;
import com.tianheng.wanzhou.datacollecting.db.service.IDrawFrame1000005Service;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.FloatOperate;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import com.tianheng.wanzhou.datacollecting.util.TqlHexchange;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component(value = "jingtiaojiHandler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IDrawFrame1000005Service drawFrame1000005Service;
    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        drawFrame1000005Service = this.drawFrame1000005Service;
//        jedis = this.jedis;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 8).eq("status", 1);
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
//        // redis 线程锁 超时3秒清楚Lock
//        while(jedis.setnx("lock",String.valueOf(System.currentTimeMillis() + 3000))==0){
//            if (System.currentTimeMillis()>Long.valueOf(jedis.get("lock")) && System.currentTimeMillis()>Long.valueOf(jedis.getSet("lock",String.valueOf(System.currentTimeMillis() + 3000))) ){
//                break;
//            }else {
//                Thread.sleep(300);
//            }
//        }
//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));
//        jedis.del("lock");

        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            DrawFrame1000005 jingtiaoji = new DrawFrame1000005();
            jingtiaoji.setMachineIp(machine.getMacIp());
            jingtiaoji.setMacId(machine.getMacId());
            String data = str.substring(6, str.length() - 4);
            jingtiaoji.setTotalOutput(TqlHexchange.fz8String(data.substring(0,8)));
            jingtiaoji.setAClassProduction(TqlHexchange.fz8String(data.substring(8,16)));
            jingtiaoji.setBClassProduction(TqlHexchange.fz8String(data.substring(16,24)));
            jingtiaoji.setCClassProduction(TqlHexchange.fz8String(data.substring(32,40)));
            jingtiaoji.setDClassProduction(TqlHexchange.fz8String(data.substring(24,32)));
            jingtiaoji.setMonocularFixedLength(TqlHexchange.zcString(data.substring(40,44)));
            jingtiaoji.setTheCurrentLength(TqlHexchange.zcString(data.substring(44,48)));
            jingtiaoji.setTheCurrentSpeed(TqlHexchange.zcString(data.substring(48,52)));
            jingtiaoji.setTheCurrentRotateSpeed(TqlHexchange.zcString(data.substring(52,56)));
            jingtiaoji.setHostRunningPeed(TqlHexchange.zcString(data.substring(56,60)));
            jingtiaoji.setHostAccelerationTime(TqlHexchange.zcString(data.substring(60,64)));
            jingtiaoji.setHostDecelerationTime(TqlHexchange.zcString(data.substring(64,68)));
            jingtiaoji.setHostInchLineSpeed(TqlHexchange.zcString(data.substring(68,72)));
            jingtiaoji.setFanDelay(TqlHexchange.zcString(data.substring(76,80)));
            jingtiaoji.setFullBarrelWarning(TqlHexchange.zcString(data.substring(80,84)));
            jingtiaoji.setCorrectionFactor(TqlHexchange.zcString(data.substring(84,88)));
            jingtiaoji.setFillTubeDelay(TqlHexchange.zcString(data.substring(96,100)));
            jingtiaoji.setDraftMultiple(TqlHexchange.zcString(data.substring(100,104)));
            jingtiaoji.setElectronStripBreakingA(TqlHexchange.zcString(data.substring(120,124)));
            jingtiaoji.setElectronStripBreakingB(TqlHexchange.zcString(data.substring(128,132)));
            jingtiaoji.setElectronStripBreakingC(TqlHexchange.zcString(data.substring(136,140)));
            jingtiaoji.setElectronStripBreakingK(TqlHexchange.zcString(data.substring(144,148)));
            jingtiaoji.setStandardWeight(TqlHexchange.fz8String(data.substring(200,208)));
            jingtiaoji.setTestWeight(TqlHexchange.fz8String(data.substring(208,216)));
            jingtiaoji.setAShift(String.valueOf(TqlHexchange.hexString2binaryString(data.substring(160,164)).charAt(15)));
            jingtiaoji.setBShift(String.valueOf(TqlHexchange.hexString2binaryString(data.substring(160,164)).charAt(14)));
            jingtiaoji.setCShift(String.valueOf(TqlHexchange.hexString2binaryString(data.substring(160,164)).charAt(13)));
            jingtiaoji.setDShift(String.valueOf(TqlHexchange.hexString2binaryString(data.substring(160,164)).charAt(12)));


            drawFrame1000005Service.saveOrUpdate(jingtiaoji);

        }finally {
            ReferenceCountUtil.release(msg);
        }
        ctx.channel().close();
        ctx.close();

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
